/*
 * @Author: yangzonglong
 * @Date: 2021-03-01 13:18:46
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 18:06:43
 * @Auditor:
 */
import React, { useCallback, useState, useImperativeHandle, forwardRef, useEffect, useRef } from 'react';
import { Form, Input, InputRef } from 'antd';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from '../../interface';
import { FormItemProps } from '../components/InputFormItemController';

export interface ScanProps extends CanvasItemProps {
  formItemProps?: FormItemProps;
  scanProps: any;
  disabled?: boolean;
  initialValue?: any;
}

interface RefProps {
  getData(): any;
}

const App = (props: ScanProps, ref: React.Ref<RefProps>) => {
  const temp = useRef('');
  const refs = useRef<InputRef>(null);



  const { initialValue, disabled, formItemProps, domComplete, scanProps, controlRefs, ...canvasProps } = props;

  useEffect(() => {
    if (initialValue) {
      setValue(initialValue);
    }
  }, [initialValue]);

  const [value, setValue] = useState('');

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  const keydown = useCallback((e: KeyboardEvent | any, onChange: (v: string) => void) => {
    const key = e.key;
    if (key !== 'Enter') return;
    const code = temp.current.replace(/Shift/g, '');
    code && onChange(code);
    setValue(code);
    temp.current = '';
  }, []);

  useImperativeHandle(ref, () => ({
    getData() {
      return value;
    },
    setData(initialValue: any) {
      setValue(initialValue);
    },
    focus() {
      refs.current?.focus();
    }
  }));

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;
  const placeholder = localStorage.i18nextLng === 'en' ? scanProps?.placeholderEn : scanProps?.placeholder;

  const CombineNode = (props: any) => {
    return <Input
      ref={refs}
      defaultValue={value}
      onKeyDown={(e) => keydown(e, props.onChange)}
      onChange={(e) => {
        temp.current = e.target.value;
      }}
      disabled={disabled || scanProps?.disabled}
      placeholder={disabled || scanProps?.disabled ? "" : placeholder}
    />;
  };

  return (
    <Form.Item {...canvasProps} {...formItemProps} label={label}>
      <CombineNode />
    </Form.Item>
  );
};

export default forwardRef(App);
